<?php

namespace app\model\common;

use app\model\auth\Admin;
use app\model\platform\CompanyModel;
use liliuwei\think\Auth;
use think\facade\Request;
use think\Model;
use think\Paginator;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;

class CommonModel extends Model
{
    /**
     * 查询不到数据的异常处理函数
     * @param $message
     * @throws DataNotFoundException
     */
    public function dataNotFoundExceptionHandle($message)
    {
        throw new DataNotFoundException($message);
    }

    /**
     * 获取列表
     * @param array $where 查询条件
     * @param int $pageSize 单页的记录数
     * @param array $order 排序条件
     * @return Paginator 带分页的列表
     * @throws DbException
     */
    public function getList($where, $pageSize, $order = ['sort' => 'asc'])
    {
        $list = $this->withSearch(['auth'])
            ->where($where)
            ->order($order)
            ->paginate([
                'query' => Request::get(),
                'list_rows' => $pageSize,
            ]);

        return $list;
    }

    /**
     * 获取所有数据, 数据不存在返回空数组 不抛异常
     * @param array $where 查询条件
     * @param array $order 排序条件
     * @return mixed|array
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function getAllData($where = [], $order = [])
    {
        // 数据不存在返回空数组 不抛异常
        $data = $this
            ->where($where)
            ->order($order)
            ->failException(false)
            ->select();
        return is_object($data) ? $data->toArray() : $data;
    }

    /**
     * 获取单条数据(没有数据的时候返回null)
     * @param array $where 查询条件
     * @return array|Model|null
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getOneData($where)
    {
        $data = $this
            ->where($where)
            ->find();
        return empty($data) ? $data : $data->toArray();
    }

    /**
     * 获取某个字段的值
     * @param array $where 查询条件
     * @param string $field 要查询的字段
     * @return mixed
     */
    public function getField($where, $field)
    {
        $data = $this
            ->where($where)
            ->value($field);
        return $data;
        // if(empty($data)){
        //     if(is_numeric($data)) {
        //         return $data;
        //     }else{
        //         return $this->dataNotFoundExceptionHandle('没有查询到数据');
        //     }
        // }else{
        //     return $data;
        // }
    }

    public function getFields($where, $fields)
    {
        return $this->withSearch(['auth'])->where($where)->field($fields)->select()->toArray();
    }

    /**
     * 获取某个列的值
     * @param array $where 查询条件
     * @param string $field 要查询的字段
     * @return mixed
     */
    public function getColumn($where, $field)
    {
        $data = $this
            ->where($where)
            ->column($field);
        // halt($data);
        // return is_array($data) && count($data) > 0
        //     ? $data
        //     : $this->dataNotFoundExceptionHandle('没有查询到数据');
        return $data;
    }

    /**
     * 新增数据
     * @param array $data
     * @return CommonModel|Model
     */
    public function addData(array $data)
    {

        return $this->create($data);
    }

    /**
     * 更新数据
     * @param array $data
     * @throws DataNotFoundException
     */
    public function saveData(array $data)
    {
        return $this->update($data) ?: $this->dataNotFoundExceptionHandle('没有修改任何数据');
    }

    /**
     * 删除数据
     * @param int $id
     * @return bool|void
     * @throws \Exception
     * @throws DataNotFoundException
     */
    public function deleteData(int $id)
    {
        // 如果id不大于0, 则报错
        if ($id <= 0) {
            throw new \LogicException('请选择正确的记录进行删除');
        }

        // 如果查找不到记录, 则报错
        $result = $this->find($id);
        if (empty($result)) {
            $this->dataNotFoundExceptionHandle('请选择正确的记录进行删除');
        }
        return $result->delete();
    }

    /**
     * 软删除数据
     * @param int $id
     * @return bool
     * @throws DbException
     * @throws \Exception
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function softDeleteData($id)
    {
        $result = $this->find($id);
        if (empty($result)) {
            $this->dataNotFoundExceptionHandle('请选择正确的记录进行删除');
        }
        return $result->delete();
    }

    public static function redis()
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', 6379);
        $redis->auth('yylhlzyh280');
        return $redis;
    }

    /**添加搜索条件
     * @param $query
     * @param $value
     * @param $data
     */
    public function searchAuthAttr($query, $value, $data)
    {
        if (session('group_id') != 1) {
            $query->where('company_id', session('company_id'));
        } elseif (Request::get('company_id'))
            $query->where('company_id', Request::get('company_id'));
    }

    public static function onBeforeInsert(Model $model)
    {
        if (session('group_id') != 1) {
            $model->company_id = session('company_id');
        }
        $model->add_user = session('admin_id');
    }

    public static function onBeforeDelete(Model $model)
    {
        if (session('group_id') != 1 && $model->company_id && $model->company_id != session('company_id')) {
            return false;
        }
    }

    public function company()
    {
        return $this->belongsTo(CompanyModel::class, 'company_id', 'company_id');
    }

    public function adduser()
    {
        return $this->belongsTo(Admin::class, 'add_user');
    }
}
